package com.doushu.websocket.service.impl;

import com.doushu.websocket.common.dto.ResultDto;
import com.doushu.websocket.common.dto.ResultDtoFactory;
import com.doushu.websocket.controller.WebSocketServer;
import com.doushu.websocket.service.MsgService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MsgServiceImpl implements MsgService {

    @Override
    public ResultDto push(String shopId, String token, String type,String msg) {
        if(type.equals("getInit")){
            for (String key:WebSocketServer.webSocketMap.keySet()){
                if(key.split("_")[0].equals(shopId)){
                    try{
                        WebSocketServer.webSocketMap.get(key).sendMessage(msg);
                        return ResultDtoFactory.toAck("success", true);
                    }catch (IOException e){
                        return ResultDtoFactory.toNack("消息发送出错");
                    }
                }
            }
        }else if(WebSocketServer.webSocketMap.get(shopId+"_"+token)!=null){
            try{
                WebSocketServer.webSocketMap.get(shopId+"_"+token).sendMessage(msg);
                return ResultDtoFactory.toAck("success", true);
            }catch (IOException e){
                return ResultDtoFactory.toNack("消息发送出错");
            }
        }
        return ResultDtoFactory.toNack("此店铺没有客户端在线");
    }

    @Override
    public ResultDto allUserKey() {
        List<String> keys = new ArrayList<String>();
        for (String key:WebSocketServer.webSocketMap.keySet()){
            keys.add(key);
        }
        return ResultDtoFactory.toAck("success",keys);
    }

    @Override
    public ResultDto pushAll(String msg) {
        for (ConcurrentHashMap.Entry<String,WebSocketServer> entry:WebSocketServer.webSocketMap.entrySet()) {
            try{
                entry.getValue().sendMessage(msg);
            }catch (IOException e){
                return ResultDtoFactory.toNack("消息发送出错");
            }
        }
        return ResultDtoFactory.toAck("success", true);
    }
}
